/* ----------------------------------------------------------
 * 文件名称：FXMLDocumentController.java
 * 
 * 作者：秦建辉
 * 
 * 微信：splashcn
 * 
 * 博客：http://www.firstsolver.com/wordpress/
 * 
 * 开发环境：
 *      NetBeans 8.1
 *      JDK 8u102
 *      
 * 版本历史：
 *      V1.1    2016年08月10日
 *              SDK更新
 *
 *      V1.0    2015年12月10日
 *              验证客户端
------------------------------------------------------------ */

package com.huajx.client;

import Com.FirstSolver.Splash.FaceIdProtocolCodecFactory;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
//import javafx.scene.control.Alert;
//import javafx.scene.control.Alert.AlertType;
//import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.huajx.http.kit.HttpKit;
import com.huajx.kit.DateKit;
import com.huajx.kit.FileKit;
import com.huajx.kit.Prop;
import com.huajx.kit.PropKit;
import com.huajx.kit.StrKit;

@SuppressWarnings("restriction")
public class FXMLDocumentController extends IoHandlerAdapter implements Initializable {
	private final String DeviceCharset = "GBK";

	// @FXML
	//// private TextField textFieldDeviceIP;
	//
	// @FXML
	//// private TextField textFieldDevicePort;
	//
	// @FXML
	//// private TextField textFieldSecretKey;

	@FXML
	private TextArea textAreaDeviceCommand;

	@FXML
	private TextArea textAreaAnswer;

	public final static List<String> ipAddresses = new LinkedList<>();

	private String deviceConfig = "";
	
	private boolean isFirst = true;
	private boolean isInit = false;
	
	private String serverUrl="http://localhost:8080/jxt-weixin";

//	String ipAddress;
//	int port;

	@FXML
	private void handleButtonExecuteCommand(ActionEvent event) throws Exception {
		String command = "GetDeviceInfo()";
		for (String ipport : ipAddresses) {
			if(StrKit.isBlank(ipport)){
				continue;
			}
			
			if(ipport.indexOf(":")!=-1){
				String[] arr = ipport.split(":");
				String ip = arr[0];
				int port = Integer.parseInt(arr[1]);
				
				excuteCommand(command, ip, port);
			}else{
				excuteCommand(command, ipport, 9922);
			}
		}
	}
	
	private void excuteCommand(String command, String ip, int port){
		IoConnector TcpClient = new NioSocketConnector();
		TcpClient.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new FaceIdProtocolCodecFactory(DeviceCharset, false, false)));
		TcpClient.setHandler(this);

		// 设置读超时等待时间为60秒
		TcpClient.getSessionConfig().setReaderIdleTime(60);

		// 建立连接
		ConnectFuture ConnFuture = TcpClient.connect(new InetSocketAddress(ip, port));
		try {
			ConnFuture.await(60);
			// 发送查询命令
			if (ConnFuture.isConnected()) { // 连接设备成功
				ConnFuture.getSession().write(command);
				
				ConnFuture.getSession().getCloseFuture().await(120);
			} else { // 连接设备失败
				String message = ip + ":" + port + " 连接设备失败！";
				printMessage(message, false);
			}
		} catch (Exception e) {
			String message = ip + ":" + port + " 获取数据异常！获取命令:" + command;
			printMessage(message, true);
		}

		TcpClient.dispose();
	}
	
	private void getRecord(String ip, int port){
		String command = "GetRecord(";
		Date date = DateKit.getDate();
		
		Date start = null;
		if(!isInit){
			if(isFirst){
				start = DateKit.startDateByDay(date, 0);
			}else{
				start = DateKit.addMinute(date, -2);
			}
		}else{
			start = DateKit.parse("2017-11-01", DateKit.pattern_ymd);
		}
		command +="start_time=\"";
		command += DateKit.format(start, DateKit.pattern_ymd_hms) + "\"";
		command += " end_time=\"";
		command += DateKit.format(date, DateKit.pattern_ymd_hms) + "\"";
		command += ")";
		
		
		printMessage(command, false);
		
		excuteCommand(command, ip, port);
	}
	
	private void getRecord(){
		for (String ipport : ipAddresses) {
			if(StrKit.isBlank(ipport)){
				continue;
			}
			
			if(ipport.indexOf(":")!=-1){
				String[] arr = ipport.split(":");
				
				getRecord(arr[0], Integer.parseInt(arr[1]));
			}else{
				getRecord(ipport, 9922);
			}
		}
		isFirst = false;
	}

	@FXML
	private void handleButtonClearAction(ActionEvent event) {
		textAreaAnswer.clear();
	}

	@FXML
	private void handleButtonSaveAction(ActionEvent event) {
		String content = textAreaDeviceCommand.getText();
		if(StrKit.isBlank(content)){
			printMessage("设备信息不能为空", true);
			return;
		}
		
		if(resetIpAddress(content)){
			FileKit.writeFile(deviceConfig, content);
			printMessage("设备信息保存成功", false);
		}

		
	}
	
	private boolean resetIpAddress(String content){
		if(StrKit.isBlank(content)){
			return false;
		}
		String[] strArr = content.split("\n");
		ipAddresses.clear();
		for (String string : strArr) {
			ipAddresses.add(string.trim());
		}
		
		return true;
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		// String SecretKey = textFieldSecretKey.getText();
		// if (!Utils.IsNullOrEmpty(SecretKey)) { // 设置通信密钥
		// FaceIdProtocolCodecFactory.setEncoderKey(session, SecretKey);
		// FaceIdProtocolCodecFactory.setDecoderKey(session, SecretKey);
		// }
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		super.messageSent(session, message);
	}

	void printMessage(Object message, boolean isClear) {
		javafx.application.Platform.runLater(new Runnable() {
			@Override
			public void run() {
				// 更新JavaFX的主线程的代码放在此处
				if(isClear){
					textAreaAnswer.setText(message.toString() + "\n");
				}else{
					textAreaAnswer.appendText(message.toString() + "\n");
				}
				
			}
		});
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		// 显示消息内容
		printMessage(message, false);
		try{
			HttpKit.post(serverUrl + "/a/hanvon", message.toString(), schoolId, schoolName);
			printMessage("数据上传成功！", false);
		}catch (Exception e) {
			printMessage("服务器访问错误，数据未上传！"+serverUrl, false);
		}

		session.closeNow();
	}

	public void printDevice() {
		javafx.application.Platform.runLater(new Runnable() {
			@Override
			public void run() {
				// 更新JavaFX的主线程的代码放在此处
				for (String string : ipAddresses) {
					textAreaDeviceCommand.appendText(string + "\n");
				}
			}
		});
	}

	/**
	 * 初始设备信息表
	 */
	private void initDeviceList() {
		try {
			deviceConfig = getClass().getClassLoader().getResource("").getPath() + "device.ini";
			deviceConfig = URLDecoder.decode(deviceConfig, "UTF-8");
			
			String content = FileKit.file2String(deviceConfig);

			printMessage("系统启动成功", false);
			
			if(resetIpAddress(content)){
				printMessage("获取设备列表成功", false);
				printDevice();
			}else{
				printMessage("设备列表未配置\n", false);
				return;
			}
		} catch (Exception e) {
			printMessage("系统启动失败：没有配置文件，请维护device.ini文件", false);
		}
	}
	
	String di_file;
	boolean isCreate=true;
	
	private void proccessInit(){
		if(isCreate){
			try{
				di_file = getClass().getClassLoader().getResource("").getPath() + "di.off";
				di_file = URLDecoder.decode(di_file, "UTF-8");
				File file = new File(di_file);
				
				if(file.exists()){
					isInit = false;
				}else{
					isInit = true;
					FileKit.writeFile(file, "off");
				}
				isCreate = false;
			}catch(Exception e){
				printMessage("系统启动失败：初始化di.off", false);
			}
		}
	}
	
	private boolean config_dev = true;
	private String schoolId;
	private String schoolName;
	private void initConfig(){
		Prop prop = PropKit.use("config.properties");
		
		config_dev = prop.getBoolean(Constant.config_dev, true);
		
		if(!config_dev){
			serverUrl = prop.get(Constant.server_url);
		}
		schoolId = prop.get(Constant.school_id);
		schoolName = prop.get(Constant.school_name);
	}

	@Override
	public void initialize(URL url, ResourceBundle rb) {
		initDeviceList();
		
		initConfig();
		
		proccessInit();

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				getRecord();
				
				if(isInit) {
					proccessInit();
					isInit=false;
				}
			}
		};
		Timer timer = new Timer();
		long delay = 5000;
		long intevalPeriod = 2 * 60 * 1000;
		timer.scheduleAtFixedRate(task, delay, intevalPeriod);
	}
}
